package com.qing.demo.netty.client;

import com.qing.demo.netty.codec.RpcDecoder;
import com.qing.demo.netty.codec.RpcEncoder;
import com.qing.demo.netty.msg.Request;
import com.qing.demo.netty.msg.Response;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author caozhipeng
 * @date 2025/8/2
 */
public class ClientSocket implements Runnable{

    private ChannelFuture future;


    @Override
    public void run() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(io.netty.channel.ChannelOption.AUTO_READ,true);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(io.netty.channel.socket.SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new RpcDecoder(Response.class),new RpcEncoder(Request.class),new MyClientHandler());
                }
            });

            ChannelFuture future1 = bootstrap.connect("127.0.0.1", 7379).sync();
            System.out.println("客户端链接success");
            this.future=future1;
            future1.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
        }

    }

    public ChannelFuture getFuture() {
        return future;
    }

    public void setFuture(ChannelFuture future) {
        this.future = future;
    }
}
